package com.springx.examples.showcase.controller;

import com.fasterxml.jackson.databind.JavaType;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Maps;
import com.springx.examples.showcase.common.domain.Message;
import com.springx.examples.showcase.common.domain.Order;
import com.springx.examples.showcase.entity.Admin;
import com.springx.examples.showcase.entity.Role;
import com.springx.examples.showcase.enums.AdminEnum;
import com.springx.examples.showcase.service.AdminRoleService;
import com.springx.examples.showcase.service.AdminService;
import com.springx.examples.showcase.service.ResourceService;
import com.springx.examples.showcase.service.RoleService;
import com.springx.examples.showcase.vo.DataTableVo;
import com.springx.examples.showcase.vo.RoleVo;
import com.springx.modules.mapper.JsonMapper;
import com.springx.modules.web.Servlets;
import com.springx.starter.utils.ConvertUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.Assert;
import org.springframework.web.bind.ServletRequestBindingException;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.*;

/**
 * Created by roman_000 on 2015/7/15.
 */
@Controller
@RequestMapping("/admin")
public class AdminController extends BaseController {
    @Autowired
    private AdminService adminService;
    @Autowired
    private RoleService roleService;

    @Autowired
    private AdminRoleService adminRoleService;

    @Autowired
    private ResourceService resourceService;

    /**
     * 入口页面
     *
     * @return
     */
    @RequestMapping("/index")
    public String index(Model model) {
        model.addAttribute("enabledItems", EnumSet.allOf(AdminEnum.IS_ENABLED.class));
        model.addAttribute("lockedItems", EnumSet.allOf(AdminEnum.IS_LOCKED.class));
        model.addAttribute(CRUMBS_ATTRIBUTE, buildCrumbsMap(null,"系统管理","用户管理"));
        return "admin/index";
    }

    /**
     * 跳转到edit页面
     *
     * @return
     */
    @RequestMapping("/edit_none")
    public String edit(Long id, Model model) {
        if (null != id) {
            Admin admin = adminService.select(id);
            model.addAttribute("admin", admin);
        }
        return "admin/edit";
    }

    /**
     * 列表页面
     *
     * @param request
     * @return
     * @throws ServletRequestBindingException
     */
    @RequestMapping("/list")
    public
    @ResponseBody
    DataTableVo<Admin> list(HttpServletRequest request) throws ServletRequestBindingException {
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
        PageRequest pageRequest = initPageRequest(request);
        Page<Admin> page = adminService.selectPage(searchParams, null, pageRequest);
        DataTableVo<Admin> dataTableVo = new DataTableVo(request, page);
        return dataTableVo;
    }

    @RequestMapping(value = "/insert")
    public
    @ResponseBody
    Message insert(@Valid Admin admin) {
        admin.setCreateDate(new Date());
        admin.setIsLocked(false);
        admin.setIsEnabled(true);
        admin.setLoginFailureCount(0);
        adminService.entryptPassword(admin);
        adminService.insert(admin);
        Message message = new Message(Message.StatusType.SUCCESS, "保存成功");
        return message;
    }

    @RequestMapping("/delete")
    public
    @ResponseBody
    Message delete(@RequestParam(value = "ids[]") Long[] ids) {
        adminService.delete(ids);
        Message message = new Message(Message.StatusType.SUCCESS, "删除成功");
        return message;
    }

    @RequestMapping("/update")
    public
    @ResponseBody
    Message update(@Valid Admin admin) {
        Assert.notNull(admin.getId(), "参数错误");
        Admin editAdmin = adminService.select(admin.getId());
        if (editAdmin != null) {
            editAdmin.setIsEnabled(null == admin.getIsEnabled() ? false : admin.getIsEnabled());
            editAdmin.setName(admin.getName());
            editAdmin.setEmail(admin.getEmail());
            editAdmin.setOrganizationId(admin.getOrganizationId());
            editAdmin.setIsLocked(null == admin.getIsLocked() ? false : admin.getIsLocked());
            editAdmin.setModifyDate(new Date());
            adminService.updateByPrimaryKeySelective(editAdmin);
        }

        Message message = new Message(Message.StatusType.SUCCESS, "修改成功");
        return message;
    }

    @RequestMapping("/password/init")
    public
    @ResponseBody
    Message passwordInit(@Valid Admin admin) {
        Assert.notNull(admin.getId(), "参数错误");
        Admin editAdmin = adminService.select(admin.getId());
        if (editAdmin != null) {
            editAdmin.setModifyDate(new Date());
            adminService.entryptPassword(editAdmin);
            adminService.updateByPrimaryKeySelective(editAdmin);
        }
        Message message = new Message(Message.StatusType.SUCCESS, "密码初始化成功");
        return message;
    }

    /**
     * 用户关联角色界面
     *
     * @return
     */
    @RequestMapping("/authorization/edit")
    public String authorizationEdit(HttpServletRequest request, Model model) throws ServletRequestBindingException {
        return "admin/authorization";
    }

    /**
     * 用户关联角色界面
     *
     * @return
     */
    @RequestMapping("/authorization/list")
    public
    @ResponseBody
    DataTableVo<Role> authorizationList(Long adminId, String roleName, HttpServletRequest request) throws ServletRequestBindingException {
        Integer pageNumber = ServletRequestUtils.getIntParameter(request, PAGE_NUMBER);
        Integer pageSize = ServletRequestUtils.getIntParameter(request, PAGE_SIZE);
        PageRequest pageRequest = new PageRequest(null == pageNumber ? 0 : pageNumber, null == pageSize ? 5 : pageSize);
        Map<String, Object> params = Maps.newHashMap();
        params.put("adminId", adminId);
        params.put("roleName", roleName);
        Page<RoleVo> page = roleService.findAdminRolePage(params, ImmutableList.of(new Order("createDate", Order.DESC)), pageRequest);
        DataTableVo<Role> dataTableVo = new DataTableVo(request, page);
        return dataTableVo;
    }

    /**
     * 用户关联角色界面
     *
     * @return
     */
    @RequestMapping("/authorization/insert")
    public
    @ResponseBody
    Message authorizationInsert(String ids, Long adminId, HttpServletRequest request) throws ServletRequestBindingException {
        Assert.notNull(adminId, "参数错误");
        Map<String, String> params = Maps.newHashMap();
        if (StringUtils.isNotBlank(ids)) {
            JsonMapper mapper = JsonMapper.nonEmptyMapper();
            String result = StringEscapeUtils.unescapeHtml4(ids);
            params = mapper.fromJson(result, HashMap.class);
        }
        adminRoleService.insert(params, adminId);
        Message message = new Message(Message.StatusType.SUCCESS, "保存成功");
        return message;
    }

}
